from django.middleware.locale import LocaleMiddleware
from django.utils.cache import patch_vary_headers
from django.utils import translation
from django.conf import settings
#from django.utils.translation import check_for_language, activate, to_locale, get_language

def get_language_from_request_path(request):
    try:
        lang = request.META['PATH_INFO'][1:3]
        if lang and translation.check_for_language(lang):
            return lang
        else:
            return ''
    except:
        return ''
    

class PathLocaleMiddleware(LocaleMiddleware):
    def process_request(self, request):
        language = translation.get_language_from_request(request)
        lang = get_language_from_request_path(request)
        if lang:
            language=lang
            if hasattr(request, 'session'):
                request.session['django_language'] = language
            else:
                response.set_cookie(settings.LANGUAGE_COOKIE_NAME, language)
        translation.activate(language)
        request.LANGUAGE_CODE = translation.get_language()


    def process_response(self, request, response):
        patch_vary_headers(response, ('Accept-Language',))
        if 'Content-Language' not in response:
            response['Content-Language'] = translation.get_language()
        translation.deactivate()
        return response
        
        
        